'''
健康随e保重疾保障计划（成年人版）
'''

import sys
sys.path.append('../')
from common.config import *
from db.mysql import MysqlClient
from itertools import product
import execjs
from common.helper import Helper
class Spider( object ):

    def __init__(self):

        self.mysql = MysqlClient()
        self.name = "健康随e保重疾保障计划（成年人版）"
    # 生产产品数据
    def genProductInfo(self):
        plan = {
            "planA":{
                # 年龄段
                "year":[str(i) for i in range(18,36)],
                # 性别
                "gender":["M","F"],
                #保额
                "money":[str(i) + "0000" for i in range(5,55,5)],
                #保险期间
                "expire":["20年","25年","30年","70岁","80岁","终身"],
                #缴费间隔 0 一次行缴清
                "interval":["0","3","5","10","20"],
                #交款类型
                "payType":["月缴","年缴"]
            },
            "planB": {
                # 年龄段
                "year": [str(i) for i in range(36, 40)],
                # 性别
                "gender": ["M", "F"],
                # 保额
                "money": [str(i) + "0000" for i in range(5, 55, 5)],
                # 保险期间
                "expire": ["20年", "25年", "70岁", "80岁", "终身"],
                # 缴费间隔 0 一次行缴清
                "interval": ["0", "3", "5", "10", "20"],
                # 交款类型
                "payType": ["月缴", "年缴"]
            },
            "planC": {
                # 年龄段
                "year": [str(i) for i in range(41, 46)],
                # 性别
                "gender": ["M", "F"],
                # 保额
                "money": [str(i) + "0000" for i in range(5, 55, 5)],
                # 保险期间
                "expire": ["20年", "70岁", "80岁", "终身"],
                # 缴费间隔 0 一次行缴清
                "interval": ["0", "3", "5", "10"],
                # 交款类型
                "payType": ["月缴", "年缴"]
            },
            "planD": {
                # 年龄段
                "year": [str(i) for i in range(46, 51)],
                # 性别
                "gender": ["M", "F"],
                # 保额
                "money": [str(i) + "0000" for i in range(5, 55, 5)],
                # 保险期间
                "expire": ["70岁", "80岁", "终身"],
                # 缴费间隔 0 一次行缴
                "interval": ["0", "3", "5"],
                # 交款类型
                "payType": ["月缴", "年缴"]
            },
        }
        num = 0
        for k in plan:

            for v in product( plan[k]["year"],plan[k]["gender"],plan[k]["money"],plan[k]["expire"],plan[k]["interval"],plan[k]["payType"]):
                num+=1
                self.mysql.cursor.execute(
                    domain[self.name]["insert_sql"].format(

                        v[0],v[1],v[2],v[3],v[4],v[5]
                    )
                )
                self.mysql._conn.commit()
                print(

                    domain[self.name]["insert_sql"].format(

                        v[0], v[1], v[2], v[3], v[4], v[5]
                    )

                )


    #计算保费
    def CalcPremium(self,dt=None):

        js = open('./'+self.name+'.js',mode="r",encoding="utf-8").read()

        cxt = execjs.compile( js )

        try:

            if "年" in dt["expire"]:

                print("~~~~~~投保至:%s~~~~~~~" % dt["expire"])

                expire = dt["expire"].replace("年","")


            elif "岁" in dt["expire"]:

                print("~~~~~~投保至:%s~~~~~~~" % dt["expire"])

                expire = dt["expire"].replace("岁","a")

            else:

                print("~~~~~~投保至:%s~~~~~~~" % dt["expire"])

                expire = "106a"

            data = {

                "year":dt["year"],
                "gender":"1" if dt["gender"] == "M" else "2",
                "money":int(int(dt["money"])/10000),
                "expire":expire,
                "interval":dt["interval"],
                "payType":"1" if dt["payType"] == "月缴" else "12",
            }

            result = cxt.call("CalcPremium",data)

            if result["code"] == "0":

                price = Helper.decimalParse( result["premium"] )

                data = {
                    "name":self.name,
                    "id":dt["id"],
                    "price":price
                }
                self.mysql.updatePrice( data )
            else:
                data = {
                    "name": self.name,
                    "id": dt["id"],
                    "state":3
                }

                self.mysql.updateTask( data )
                print("/*产品价格更新失败:%d*/"%dt["id"])
        except:

            data = {
                "name": self.name,
                "id": dt["id"],
                "state": 3
            }

            self.mysql.updateTask(data)
            print("/*产品价格更新失败:%d*/" % dt["id"])
    def main(self):

        while True:

            # 随机领取一条数据
            dt = self.mysql.randTask(self.name)

            if not dt:
                print("产品价格抓取完成~~~")

                return

                # 任务执行状态
            data = {
                "name": self.name,
                "id": dt["id"],
                "state": 1
            }
            self.mysql.updateTask(data)

            self.CalcPremium(dt)
